package net.ebakker.feededitor;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Map;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.ebakker.feededitor.compose.FeedComposer;
import net.ebakker.feededitor.database.PostgresConnector;
import net.ebakker.feededitor.database.PostgresInserter;
import net.ebakker.feededitor.database.PostgresQuerier;
import net.ebakker.feededitor.database.PostgresRemover;

import org.json.JSONException;

/**
 * Servlet implementation class FeedEditor
 */
@WebServlet("/FeedEditor")
public class FeedEditor extends HttpServlet {
	private static final String PROPERTIES_FILE = "/opt/feedEditor/postgres.properties";
	private static final long serialVersionUID = 1L;
	private Preferences preferences;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public FeedEditor() {
		super();
		preferences = new Preferences(new File(PROPERTIES_FILE));
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		Connection conn = null;
		ResultSet rs = null;
		try {
			conn = PostgresConnector.connect(preferences);
			rs = new PostgresQuerier(conn).executeQuery("SELECT id,title FROM ttrss_feeds");
			returnResponse(response, rs);
		} catch (SQLException | ClassNotFoundException e) {
			e.printStackTrace();
		} finally {
			closeDbConnection(conn, rs);
		}
	}

	private void returnResponse(HttpServletResponse response, ResultSet rs) throws IOException {
		response.setContentType("application/json");
		PrintWriter out = response.getWriter();
		String output = "";
		try {
			output = new FeedComposer().compose(rs);
		} catch (JSONException | SQLException e) {
			e.printStackTrace();
		}
		out.println(output);
	}

	private void closeDbConnection(Connection conn, ResultSet rs) {
		try {
			if (conn != null) {
				conn.close();
			}
			if (rs != null) {
				Statement st = rs.getStatement();
				st.close();
				rs.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		Map<String, String[]> map = request.getParameterMap();
		Connection conn = null;
		try {
			conn = PostgresConnector.connect(preferences);
			String type = map.get("type")[0];
			if ("add".equals(type)) {
				insertNewMovie(map, conn);
			} else if ("remove".equals(type)) {
				removeFeed(map, conn);
			}
			returnSuccessResponse(response);
		} catch (ClassNotFoundException | SQLException e) {
			e.printStackTrace();
			returnFailureResponse(e, response);
		} finally {
			closeDbConnection(conn, null);
		}
	}

	private void removeFeed(Map<String, String[]> map, Connection conn) throws SQLException {
		int id = Integer.parseInt(map.get("id")[0]);
		new PostgresRemover().remove(id, conn, preferences);
	}

	public void insertNewMovie(Map<String, String[]> map, Connection conn) throws SQLException,
			UnsupportedEncodingException {
		String movie = map.get("title")[0];
		new PostgresInserter().insert(movie, conn, preferences);
	}

	private void returnFailureResponse(Exception e, HttpServletResponse response)
			throws IOException {
		PrintWriter writer = response.getWriter();
		writer.println("{error:" + e.getMessage() + "}");
	}

	private void returnSuccessResponse(HttpServletResponse response) throws IOException {
		PrintWriter writer = response.getWriter();
		writer.println("{result:OK}");
	}
}
